package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.*
import android.view.KeyEvent
import android.view.View
import androidx.fragment.app.FragmentTransaction
import com.glory.cqaospda.R
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.view.fragment.HomeFragment
import com.glory.cqaospda.view.fragment.MessageQueryFragment
import com.glory.cqaospda.viewmodel.HomeModel
import com.glory.mvvmnet.base.BaseActivity
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_DownloadFragmentDialog
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_VersionEntity
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_SharePreferencesUtils
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_Utils
import kotlinx.android.synthetic.main.activity_home.*


class HomeActivity() : BaseActivity<HomeModel>(), View.OnClickListener, Parcelable {

    var homeFragment: HomeFragment? = null
    var messageQueryFragment: MessageQueryFragment? = null
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when(msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@HomeActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }

    constructor(parcel: Parcel) : this() {

    }

    override fun layoutId(): Int {
        return R.layout.activity_home
    }

    override fun initView(savedInstanceState: Bundle?) {
        tvUserName.text = Constant.UserName
        tvTitle.text = "功能管理"
        messageText.setOnClickListener(this)
        homeText.setOnClickListener(this)
        FreeApi_ActivityManager.getActivityManager().addActivity(this)

        val instance = MyApp.instance
        instance!!.handler = handler
    }

    override fun initData() {
        Constant.eqpid = ""
        val beginTransaction = supportFragmentManager.beginTransaction()
        selected()
        homeText.setSelected(true)
        if(homeFragment==null){
            homeFragment  = HomeFragment()
            beginTransaction.add(R.id.fragment_container, homeFragment!!)
        }else{
            beginTransaction.show(homeFragment!!)
        }
        beginTransaction.commit()

        viewModel.defUI.callObserve.observe(this) {
            if (!Constant.okgoError){
                when (it.type) {
                    2 -> {
                        val manager: PackageManager = this.packageManager
                        var info: PackageInfo? = null
                        try {
                            info = manager.getPackageInfo(this.packageName, 0)
                        } catch (e: PackageManager.NameNotFoundException) {
                            e.printStackTrace()
                        }
                        val version = info!!.versionName

                        val freeuiVersionentity = it.item as FreeUI_VersionEntity
                        freeuiVersionentity.currentVersion = version
                        FreeApi_SharePreferencesUtils.setSharePre(
                            "SystemSet",
                            "FILE_URL_DEBUG",
                            freeuiVersionentity.downUrl,
                            MyApp.app
                        )
                        val code =
                            FreeApi_Utils.compareVersion(version, freeuiVersionentity.version)
                        if (code == -1) {
                            val downloadFragmentDialog = FreeUI_DownloadFragmentDialog()
                            downloadFragmentDialog.setData(freeuiVersionentity)
                            downloadFragmentDialog.show(this.supportFragmentManager, "DOWNLOAD")
                        }
                    }
                }
            }else{
                Constant.okgoError = false
            }
        }

    }

    @SuppressLint("CommitTransaction")
    override fun onClick(view: View?) {

        val beginTransaction = supportFragmentManager.beginTransaction()
        hideAllFragment(beginTransaction)
        when(view){
            homeText ->{
                tvTitle.text = "功能管理"
                selected()
                homeText.setSelected(true)
                if(homeFragment==null){
                    homeFragment = HomeFragment()
                    beginTransaction.add(R.id.fragment_container, homeFragment!!)
                }else{
                    beginTransaction.show(homeFragment!!)
                }
            }
            messageText ->{
                tvTitle.text = "信息查询"
                selected()
                messageText.setSelected(true)
                if(messageQueryFragment==null){
                    messageQueryFragment = MessageQueryFragment()
                    beginTransaction.add(R.id.fragment_container, messageQueryFragment!!)
                }else{
                    beginTransaction.show(messageQueryFragment!!)
                }
            }
        }
        beginTransaction.commit()
    }

    fun selected() {
        homeText.setSelected(false)
        messageText.setSelected(false)
    }

    //隐藏所有Fragment
    fun hideAllFragment(transaction: FragmentTransaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment!!)
        }
        if (messageQueryFragment != null) {
            transaction.hide(messageQueryFragment!!)
        }
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {

    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<HomeActivity> {
        override fun createFromParcel(parcel: Parcel): HomeActivity {
            return HomeActivity(parcel)
        }

        override fun newArray(size: Int): Array<HomeActivity?> {
            return arrayOfNulls(size)
        }
    }

    override fun onResume() {
        super.onResume()

        if (Constant.isUpdate){
            viewModel.initUser(this)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1) {
            when (resultCode) {
                108 -> {
                    startActivity(LoginActivity::class.java)
                    FreeApi_ActivityManager.getActivityManager().finishAllActivity()
                }
            }
        }
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            intent.putExtra("type", "KeyEvent")
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivityForResult(intent, 1)
            return false
        }
        return super.onKeyUp(keyCode, event)
    }
}
